package org.sninwo.lnbook.uitls;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.sninwo.lnbook.base.BookException;

import com.google.gson.Gson;

public class LnBookUtils {	
	/**
	 * 抛出业务异常
	 * @param throwable
	 */
	public static void throwError(String msg){
		throw new BookException(msg);
	}

	/**
	 * 抛出业务异常
	 * @param throwable
	 */
	public static void throwError(String msg, Object... args){
		throwError(String.format(msg, args));
	}
	
	/**
	 * 抛出业务异常
	 * @param throwable
	 */
	public static void throwError(Throwable throwable){
		throw new BookException(throwable);
	}
	
	/**
	 * 将对象转换成json字符串。如果只有一个参数则直接转换，否则参数个数必须为偶数，并以奇数参数为属性以偶数参数为值转换。
	 */
	public static String toJson(Object... args){
		Gson gson = new Gson();
		if (args.length == 0){
			return "{}";
		}
		else if (args.length == 1){
			return gson.toJson(args[0]);
		}
		if (args.length % 2 != 0){
			throw new RuntimeException("调用BookUtils.toJson()方法参数个数必须为偶数");
		}
		Map<String, Object> map = new HashMap<String, Object>(args.length / 2);
		for (int i = 0; i < args.length; i += 2){
			map.put(args[i].toString(), args[i + 1]);
		}
		return new Gson().toJson(map);
	}
	
	public static String toExtSuccessJson(Object obj){
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("success", true);
		result.put("data", obj);
		return toJson(result);
	}
	
	/**
	 * 拷贝对象。方便gson转换hibernate get出来的代理对象。
	 * 如果拷贝出错返回null。
	 */
	@SuppressWarnings("unchecked")
	public static <X> X cloneBean(Object obj){
		try{
			return (X) BeanUtils.cloneBean(obj);
		}
		catch(Exception e){
			
		}
		return null;
	}
}
